﻿using System;
using System.Windows;
using Winform = System.Windows.Forms;
using Interop = System.Windows.Interop;
using Microsoft.Win32;

using System.ComponentModel.Composition;


namespace DailyFx.UI
{
	[Export(typeof(IExplorer))]
	[PartCreationPolicy(CreationPolicy.NonShared)]
	public class FileExplorer : IExplorer
	{
		public const UInt32 MODE_FILE_OPEN = 1;
		public const UInt32 MODE_FILE_SAVE = 2;
		public const UInt32 MODE_FOLDER_BROWSE = 3;


		private class Win32Window : Winform.IWin32Window
		{
			private IntPtr handle;// = 0x0000;

			public Win32Window (IntPtr handle)
			{
				this.handle = handle;
			}

			IntPtr Winform.IWin32Window.Handle
			{
				get { return handle; }
			}
		}


		/// <summary>
		///		Simply use embedded FileDialog.FileName
		/// </summary>
		public string FilePath
		{
			get;
			set;
		}

		/// <summary>
		///		Simply use embedded FileDialog.Filter
		/// </summary>
		public string Filter
		{
			get;
			set;
		}

		/// <summary>
		///		Simply use embedded FileDialog.InitialDirectory
		/// </summary>
		public string InitialDirectory
		{
			get;
			set;
		}

		/// <summary>
		/// 
		/// </summary>
		public bool? Show ( Window owner, UInt32 mode )
		{
			if ( mode == MODE_FOLDER_BROWSE)
			{
				
				Winform.FolderBrowserDialog fd = new Winform.FolderBrowserDialog();
				
				if ( !String.IsNullOrEmpty(InitialDirectory))
					fd.SelectedPath = InitialDirectory;
				else
					fd.RootFolder = Environment.SpecialFolder.MyComputer;

				Interop.HwndSource src = PresentationSource.FromVisual(owner) as Interop.HwndSource;
				Winform.IWin32Window win = src == null ? null : new Win32Window(src.Handle);

				Winform.DialogResult rt = fd.ShowDialog( win);
				if ( rt == Winform.DialogResult.OK) 
				{
					this.FilePath = fd.SelectedPath;
					return true;
				}
				else if (rt == Winform.DialogResult.None) // still running
					return null;
				else // not Okey .
				{
					// this.FilePath = String.Empty;
					return false;
				}
			}
			else
			{
				// embedded FileDialog to pass back correctly selected values through
				FileDialog fd = null;

				if ( mode == MODE_FILE_OPEN) {
					fd = new OpenFileDialog();
				}
				else if (mode == MODE_FILE_SAVE) {
					fd = new SaveFileDialog();
				}
				else {
					// throw;
				} 
				//

				// Set embedded Filter
				if ( !String.IsNullOrEmpty(this.Filter) )
					fd.Filter = this.Filter;

				// Set embedded InitialDirectory
				if ( !String.IsNullOrEmpty(this.InitialDirectory) )
					fd.InitialDirectory = this.InitialDirectory;
				
				//return results
				bool? result = fd.ShowDialog( owner);
				this.FilePath = fd.FileName;

				return result;
			}
		}
	}
}
